#include <Arduino.h> 
// 定义DRV8833控制引脚 (可根据需要修改)
const int AIN1 = 18;  // PWM引脚
const int AIN2 = 19;  // PWM引脚
const int BIN1 = 4;  // PWM引脚 (可选)
const int BIN2 = 5;  // PWM引脚 (可选)
const int nSLEEP = 34; // 使能引脚

// PWM设置
const int freq = 5000;     // PWM频率(Hz)
const int resolution = 8;   // 8位分辨率(0-255)
void motorA(int speed);
void setup() {
  // 配置PWM
  ledcSetup(0, freq, resolution); // 通道0用于AIN1
  ledcSetup(1, freq, resolution); // 通道1用于AIN2
  ledcSetup(2, freq, resolution); // 通道2用于BIN1 (可选)
  ledcSetup(3, freq, resolution); // 通道3用于BIN2 (可选)
  
  // 绑定PWM通道到GPIO
  ledcAttachPin(AIN1, 0);
  ledcAttachPin(AIN2, 1);
  ledcAttachPin(BIN1, 2);  // (可选)
  ledcAttachPin(BIN2, 3);  // (可选)
  
  // 配置使能引脚
  pinMode(nSLEEP, OUTPUT);
  digitalWrite(nSLEEP, HIGH); // 启用驱动器
  
  Serial.begin(115200);
  Serial.println("ESP32 DRV8833 Motor Control Ready");
}

void loop() {
  // 演示不同速度
  for(int speed = 0; speed <= 100; speed += 10) {
    Serial.print("Forward speed: ");
    Serial.println(speed);
    motorA(speed);
    delay(500);
  }
  
  motorA(0);
  delay(1000);
  
  for(int speed = 0; speed >= -100; speed -= 10) {
    Serial.print("Reverse speed: ");
    Serial.println(speed);
    motorA(speed);
    delay(500);
  }
  
  motorA(0);
  delay(1000);
}

// 控制电机A速度 (-100到100)
void motorA(int speed) {
  speed = constrain(speed, -100, 100);
  
  if(speed > 0) {
    // 正转
    ledcWrite(0, map(speed, 0, 100, 0, 255));
    ledcWrite(1, 0);
  } else if(speed < 0) {
    // 反转
    ledcWrite(0, 0);
    ledcWrite(1, map(-speed, 0, 100, 0, 255));
  } else {
    // 停止
    ledcWrite(0, 0);
    ledcWrite(1, 0);
  }
}

// 控制电机B速度 (-100到100) - 可选
void motorB(int speed) {
  speed = constrain(speed, -100, 100);
  
  if(speed > 0) {
    ledcWrite(2, map(speed, 0, 100, 0, 255));
    ledcWrite(3, 0);
  } else if(speed < 0) {
    ledcWrite(2, 0);
    ledcWrite(3, map(-speed, 0, 100, 0, 255));
  } else {
    ledcWrite(2, 0);
    ledcWrite(3, 0);
  }
}